<template>
    <div class="app-container" v-loading="loading" >
        <div class="search-container contc-box">
			<div class="contc-left">
				<el-form ref="queryFormRef" :model="queryParams" :inline="true">
					<el-form-item >
						<el-input v-model="queryParams.name"  placeholder="请输入类目名称" clearable />
					</el-form-item>
					<el-form-item>
						<el-button @click="handleQuery" type="primary"> <template #icon><i-ep-search /></template>查询</el-button>  
					</el-form-item>
				</el-form>
			</div>
			<div class="contc-right">
				<actionbar @handleRefresh="resetQuery()" :columns="false" ></actionbar>  
			</div>
        </div>
        <el-card shadow="never" >
			<div class="action-row">
                <el-button  v-hasPerm="['asset.Classs/save']" type="primary" plain @click="handleDo('','act_add')"><template #icon><i-ep-plus /></template>新增</el-button>
			</div>
            <el-table 
					:data="dataList"  
					:tree-props="{
					children: 'children',
					hasChildren: 'hasChildren'}" 
					row-key="id" 
					default-expand-all
					border>
				<el-table-column type="index" label="序号" align="center" width="80" />		
                <el-table-column label="类目名称" min-width="200">
                    <template #default="scope">
                        {{ scope.row.class_name }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" align="center" label="操作" width="250">
                    <template #default="scope">
						<el-button type="primary"  link size="small"
						    @click.stop="handleDo(scope.row,'act_edit')">
						    <template #icon><i-ep-edit /></template> 修改
						</el-button>
                        <el-button type="primary" v-hasPerm="['asset.Classs/save']"  link size="small"
                            @click.stop="handleDo(scope.row,'act_add2')">
                            <template #icon><i-ep-plus /></template> 新增
                        </el-button>
                        <el-button  type="primary" link
						
                            size="small" v-hasPerm="['asset.Fields/index']" @click.stop="hadleShowFeild(scope.row)">
                            <template #icon><i-ep-discount /></template> 字段
                        </el-button>
                      <el-button  type="danger" v-hasPerm="['asset.Fields/delete']" link size="small"
                            @click.stop="handleDo(scope.row,'act_del')"> <template #icon><i-ep-delete /></template> 删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 新增类目 -->
        <el-dialog 
                v-model="dialogFormVisible" 
                :close-on-click-modal="false" 
                :close-on-press-escape="false"
                class="elDiaLog"
                lock-scroll 
                :title="formText" 
                width="1000px" 
                @close="dialogFormVisible =false">

				<el-form ref="dataFormRef" :rules="formRules" :model="formTemp" label-width="130px">
					<el-form-item required label="父级菜单" prop="pid">
						<el-tree-select
						v-model="formTemp.pid"
						placeholder="选择上级菜单"
						:data="menuOptions"
						:props="{
							label: 'class_name',
							children: 'children',
							value: 'id'}"
						filterable
						check-strictly
						:render-after-expand="false"
						:disabled="['act_edit','act_add2'].includes(dialogStatus)"/>
					</el-form-item>
					<el-form-item required label="类目名称" prop="class_name">
						<el-input v-model="formTemp.class_name" placeholder="请输入类目名称" />
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button type="primary" @click="handleSubmit"  v-no-more-click >确定</el-button>
						<el-button @click="dialogFormVisible =false">取消</el-button>
					</div>
				</template>
        </el-dialog>
        
 
        <!-- 所有字段 -->
        <el-dialog 
                v-model="dialogAddList.visible" 	
                :close-on-click-modal="false" 
                :close-on-press-escape="false"
                class="elDiaLog"
                lock-scroll 
                :title="`${dialogAddList.cell.class_name}-所有字段`" 
                width="1000px" 
                :destroy-on-close="true"
                @close="handleCancleList">
            <fieldcom :cell="dialogAddList.cell" :menuOptions="menuOptions"></fieldcom>
        </el-dialog>

    </div>
</template>
<script setup lang="ts">

defineOptions({
    name: "Doc",
    inheritAttrs: false,
});

import fieldcom from "./field.vue"

//接口地址
import {
    getAssetClass,
    getAssetClassAdd,
	delAssetClass,
	getAssetClassEdit
} from "@/api/asset";


// 表单模型
const cForm = {
	id:undefined,//当前类目id
	class_name: "",//类目名称
	pid: ""//类目父级菜单
}
// 验证规则
const cRules = {
	pid: [{ required: true, trigger: 'blur' ,message:"请选择父级菜单"}],
	class_name: [{ required: true, trigger: 'blur',message:"请输入类目名称" }],
}

const queryFormRef = ref(ElForm);


const queryParams = reactive({
    page: 1,
    limit: 20,//分页列表
    name: ""//类目名称
})

const dialogAddList = reactive<any>({
    visible: false,
    cell:""
});

const dataList = ref(); //列表内容
const loading = ref(false); //加载状态
const dataFormRef = ref(ElForm);
const dialogFormVisible = ref(false);
const dialogStatus = ref<string>(""); // 操作行为 formText
const formText =ref<string>(""); // 操作窗口标题
const formTemp = ref<any>(cForm);
//验证规则
const formRules = ref<any>(cRules);

//获取类目列表
const menuOptions = ref<OptionType[]>([]);

function handleCancleList(){
	dialogAddList.visible = false;
	dialogAddList.cell= false;
}
function handleQuery() {
    loading.value = true;
    getAssetClass(queryParams).then((res) => {
        console.log(res);
        dataList.value = res.data;
        menuOptions.value = [{ id: 0, class_name: "顶级菜单", children: dataList }];
    }).finally(() => {
        loading.value = false;
    })
}

// 操作
 function handleDo(row:any, act:string) {
	dialogStatus.value = act
	switch (act) {
		case 'act_add':	
			dialogFormVisible.value = true;
			formText.value = '新建类目'
			formTemp.value = JSON.parse(JSON.stringify(cForm))
			formRules.value = Object.assign({}, cRules)
			nextTick(()=>{
				setTimeout(()=>{dataFormRef.value.clearValidate();},100)
			})
			break
		case 'act_add2':
			dialogFormVisible.value = true;
			formText.value = '新建子类目'
			formTemp.value = JSON.parse(JSON.stringify(cForm))
			formTemp.value.pid = row.id
			formRules.value = Object.assign({}, cRules)
			nextTick(()=>{
				setTimeout(()=>{dataFormRef.value.clearValidate();},100)
			})
			break
		case 'act_edit':
			dialogFormVisible.value = true;
			formText.value = '修改类目';
			formTemp.value = JSON.parse(JSON.stringify(row));
			nextTick(()=>{
				setTimeout(()=>{dataFormRef.value.clearValidate();},0)
			})
			break
		case 'act_del':
			handleDelete(JSON.parse(JSON.stringify(row)))
			break
		default:
			console.log('其他按钮')
	}
}


function handleAddClass(row:any ){
    dialogFormVisible.value = true;
    formTemp.value.class_name ="";
    formTemp.value.pid = row.pid || 0;
	formTemp.value.id = row.id || undefined
	nextTick(()=>{
		setTimeout(()=>{dataFormRef.value.clearValidate();},50)
	})
}
function handleEidtClass(row?: any){
    dialogFormVisible.value = true;
    formTemp.value.class_name =row.class_name;
    formTemp.value.pid = row.pid;
	formTemp.value.id = row.id
	nextTick(()=>{
		setTimeout(()=>{dataFormRef.value.clearValidate();},50)
	})
}

// 新增类目
function handleSubmit() {
	dataFormRef.value.validate((valid:any) => {
		if (valid) {
			loading.value = true;
			const tempData = JSON.parse(JSON.stringify(formTemp.value))
			console.log(tempData);
			if (tempData.id == undefined) {
				getAssetClassAdd(tempData).then((res)=>{
				    console.log(res)
				    ElMessage({message: '添加成功', type: 'success',})
				    dialogFormVisible.value = false;
				    handleQuery();
				}).finally((res)=>{
					loading.value = false;
				})
			 } 
			 else {
				getAssetClassEdit(tempData).then((res)=>{
				    console.log(res)
				    ElMessage({ message: '修改成功',type: 'success',})
				    dialogFormVisible.value = false;
				    handleQuery();
				}).finally((res)=>{
					loading.value = false;
				})
			}
		}
	}) 
}

// 删除表单内容
function handleDelete(row:any) {
	console.log(row)
	const Ids =row.id;
	if (!Ids) {
		ElMessage.warning("请勾选删除项");
		return;
	}
	ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		loading.value = true;
		delAssetClass({id:Ids}).then(() => {
			ElMessage.success("删除成功");
			resetQuery();
		  })
		  .finally(() => (loading.value = false));
	});
}

/**
 * 所有字段
 */
function hadleShowFeild(row){
    dialogAddList.visible = true;
    dialogAddList.cell = row
}
/**
 * 重置查询
 */
function resetQuery() {
    queryFormRef.value.resetFields();
    queryParams.page = 1;
    queryParams.name = '';
    handleQuery();
}
onMounted(() => {
    handleQuery();
})

</script>
